package com.cc.visitor.service;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.servlet.KaptchaServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author chanchaw
 * @create 2024-10-10 13:00
 */
@Component
public class KaptchaService {
    @Value("${file.kaptcha.img-path}")
    private String imgPath;
    @Value("${file.kaptcha.virtual-path}")
    private String virtualPath;
    @Autowired
    private DefaultKaptcha captchaProducer;
    private Map<String, String> captchaMap = new HashMap<>();
    // 返回前端显示图片用的URL
    public Map<String, String> createKaptchaImg() throws IOException {
        //生产验证码字符串并保存到session中
        String resString = captchaProducer.createText();// 携带了结算结果：1+3=?4
        int i = resString.indexOf("?");
        String verifyCode = resString.substring(0,i+1);
        String result = resString.substring(i+1);
        BufferedImage challenge = captchaProducer.createImage(verifyCode);
        UUID uuid = UUID.randomUUID();
        String fileName = uuid + ".jpg";// 纯文件名
        String fileNameAndPath = imgPath + fileName;// 保存到本地的文件绝对路径+文件名
        File outputfile = new File(fileNameAndPath);
        ImageIO.write(challenge, "jpg", outputfile);

        Map<String, String> ret = new HashMap<>();
        String url = virtualPath.substring(0,virtualPath.length() - 2) + fileName;// url = /kaptcha/sdfsdf.jpg
        ret.put("fileName",url);
        ret.put("result", result);
        return ret;
    }
    public void getVerifyCode(String loginKey, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String verifyCode = captchaProducer.createText();// 携带了结算结果：1+3=?4
            // httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);  // 写入会话
            //redisCache.setVerifyInfo(loginKey, verifyCode);   //写入redis
            captchaMap.put(loginKey, verifyCode);//写入内存
            //log.warn("reset verify code key {}, code {}", loginKey, verifyCode);
            BufferedImage challenge = captchaProducer.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
        } catch (IllegalArgumentException | IOException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        byte[] captchaOutputStream = imgOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");

        httpServletResponse.addHeader("kaptchaResult","chanchaw");
        try (ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream()) {
            responseOutputStream.write(captchaOutputStream);
            responseOutputStream.flush();
        } catch (IOException ex) {
            //log.error("find ex in create a new verify Code", ex);
        }
    }
}
